import logging

from google.appengine.api import mail
from google.appengine.api import urlfetch
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

from django.utils import simplejson as json

import feedparser

from settings import *

class DeliverHandler(webapp.RequestHandler):
  def get(self):
    try:
      feedinput = urlfetch.fetch(RSS_FEED)
      feed_content = (feedparser.parse(feedinput.content))
  
      body = ''    
      for entry in feed_content.entries:
	      body += '<p><b>%s</b><br />%s</p>' % (entry['title'], entry['summary'])
	      logging.info(entry['title'] + ' ' + entry['summary'])
    except:
      raise Exception('Cannot fetch' + RSS_FEED)

    mail.send_mail(SENDER_EMAIL,
                   KINDLE_EMAIL,
                   'Kindle RSS',
                   body,
                   attachments=[(ATTACHMENT_NAME, body)])

application = webapp.WSGIApplication([('/deliver_rss', DeliverHandler)],
                                     debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()